package com.example.activelifecycletest.network.http;


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.activelifecycletest.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http练习
 * @author zhangding
 * @date 2022年5月6日22:28:18
 */
public class HttpActivity extends AppCompatActivity implements View.OnClickListener {
    TextView responceText;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);
        Button sendRequest = findViewById(R.id.send_request);
        responceText = findViewById(R.id.responce_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.send_request){
            sendRequestWithHttp();
        }
    }
    private void sendRequestWithHttp(){
        // 开启一个新的线程
        new Thread(() -> {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://www.bing.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuffer responce = new StringBuffer();
                    String line;
                    while ((line = reader.readLine()) != null){
                        responce.append(line);
                    }
                    runOnUiThread(() ->
                       responceText.setText(responce.toString())
                    );
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(reader != null){
                        try {
                            reader.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                    if (connection != null){
                        connection.disconnect();
                    }
                }
        }).start();
    }
}
